package com.easy.deploy.util;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;

/**
 * @Description 代码同步
 * @Date 2023/11/11 16:08
 * @Author 余乐
 **/
public class GitUtil {

    public static boolean cloneOrPullRepository(String remoteUrl, String localPath, String gitUser, String gitPassword) {
        File localDir = new File(localPath);
        if (!localDir.exists() || !localDir.isDirectory() || localDir.list().length == 0) {
            return cloneRepository(remoteUrl, localPath, gitUser, gitPassword);
        } else {
            return pullRepository(localPath, gitUser, gitPassword);
        }
    }

    private static boolean cloneRepository(String remoteUrl, String localPath, String name, String password) {
        try {
            Git.cloneRepository()
                    .setURI(remoteUrl)
                    .setDirectory(new File(localPath))
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(name, password))
                    .call();
            System.out.println("Repository cloned to " + localPath);
            return true;
        } catch (GitAPIException e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean pullRepository(String localPath, String name, String password) {
        try (Git git = Git.open(new File(localPath))) {
            PullCommand pullCmd = git.pull();
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(name, password));
            pullCmd.call();
            System.out.println("Repository pulled at " + localPath);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
